/*
 * @author: liubing
 * @Date: 2020-07-19 15:36:09
 * @desc: Quest4 走马灯效果
 */

const vs_source = `
    attribute vec4 a_Position;
    attribute vec2 a_TexCoord;
    varying vec2 v_TexCoord;
    
    void main(){
        gl_Position = a_Position;
        v_TexCoord = a_TexCoord;        
    }
    `;

const fs_source = `
    precision mediump float;

    varying vec2 v_TexCoord;
    uniform float a_distance;
    uniform sampler2D u_Sampler0;
    uniform sampler2D u_Sampler1;
    void main(){
        
        vec2 cord = v_TexCoord + vec2(-a_distance,0.0);
        vec4 color0 = texture2D(u_Sampler0,cord);
        vec4 color1 = texture2D(u_Sampler1,cord);

        gl_FragColor = color0;

        if(cord.x >= 0.0 && cord.x <= 1.0)
            gl_FragColor = color0;
        else 
            gl_FragColor = color1;

    }`;

const ANGLE_STEP = 45.0;
const COLOR_CHANGE_STEP = 50;
let g_last;

let vertex_tex_array = [
    -0.5,0.5,0.0,1.0,
    -0.5,-0.5,0.0,0.0,
    0.5,0.5,1.0,1.0,
    0.5,-0.5,1.0,0.0,
]

let textureLoaded = [];


let last_frame;
let distance = 0.0;

function moveTexCord(gl,step){
    let stride = 4
    let vertex_num = 2
    let uv_num = 2
    let idxNum = vertex_tex_array.length / stride;
    

    let now = Date.now();
    last_frame = last_frame || now;
    let elapsed = now - last_frame;
    // if (elapsed > COLOR_CHANGE_STEP) {
    if (1) {
        last_frame = now;        
        let a_distance = gl.getUniformLocation(gl.program,"a_distance")
        if (a_distance < 0) {
            console.log('Failed to get the storage location of a_distance');
            return;
        }


        distance += step;
        if (distance > 1.0 ){
            distance -= 2.0;
        }
        gl.uniform1f(a_distance,distance);
        console.log("disance",distance);
    }
    return vertex_tex_array

}

function draw(gl, n, texCooord) {

    gl.clear(gl.COLOR_BUFFER_BIT);
    
    if (textureLoaded[0] && textureLoaded[1] ){
        
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCooord), gl.STATIC_DRAW);
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
    }
}

function initVertexBuffers(gl) {

    var n = 4; 

    var verticesTexCoords = new Float32Array(
        
    )


    var vertexBuffer = gl.createBuffer();
    if (!vertexBuffer) {
        console.log('Failed to create Buffer Object');
        return -1;
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, verticesTexCoords, gl.STATIC_DRAW);


    var FSIZE = verticesTexCoords.BYTES_PER_ELEMENT;
    let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) {
        console.log("Failed to get Position");
        return -1;
    }
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 4,0);
    gl.enableVertexAttribArray(a_Position)


    var a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord');
    if (a_TexCoord < 0) {
        console.log('Failed to get the storage location of a_TexCoord');
        return -1;
    }
    gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT,false, FSIZE * 4,FSIZE * 2);
    gl.enableVertexAttribArray(a_TexCoord);  // Enable the assignment of the buffer object

    return n;
}

function initTextures(gl, n) {

    var texture0 = gl.createTexture(); // Create a texture object
    if (!texture0) {
        console.log('Failed to create the texture object -- texture0');
        return false;
    }

    let texture1 = gl.createTexture();
    if(!texture1){
        console.log("Failed to create the texture object -- texture1");
        return false
    }


    // Get the storage location of u_Sampler
    var u_Sampler0 = gl.getUniformLocation(gl.program, 'u_Sampler0');
    if (!u_Sampler0) {
        console.log('Failed to get the storage location of u_Sampler');
        return false;
    }

    let u_Sampler1 = gl.getUniformLocation(gl.program,'u_Sampler1');
    if(!u_Sampler1){
        console.log('Failed to get the storage location of u_Sampler');
        return false;
    }

    var image0 = new Image(); // Create the image object
    if (!image0) {
        console.log('Failed to create the image object');
        return false;
    }

    var image1 = new Image();
    if(!image1){
        console.log("Failed to create tie image object1");
        return false;
    }

    image0.src = './resources/sky_cloud.jpg';
    image0.onload = function () {
        loadTexture(gl, n, texture0, u_Sampler0, image0,0);
    };
    
    image1.src = './resources/star.png';
    image1.onload = function(){
        loadTexture(gl,n,texture1,u_Sampler1,image1,1);
    }
    

    return true;
}


function loadTexture(gl, n, texture, u_Sampler, image, texUnit) {

    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); // Flip the image's y axis
    // Enable texture unit0
    if (texUnit == 0)
        gl.activeTexture(gl.TEXTURE0);
    if (texUnit == 1){
        gl.activeTexture(gl.TEXTURE1);
    }
    // Bind the texture object to the target
    gl.bindTexture(gl.TEXTURE_2D, texture);

    // Set the texture parameters
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    // Set the texture image
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
    // Set the texture unit 0 to the sampler
    gl.uniform1i(u_Sampler, texUnit);

    textureLoaded[texUnit] = true;
}


function main() {

    let canvas = document.getElementById("glCanvas");
    const gl = canvas.getContext('webgl');
    if (!gl) {
        console.log("WebGL Failed");
        return;
    }
    console.log("width", canvas.width)
    console.log("height", canvas.height)
    gl.viewport(0, 0, canvas.width, canvas.height)

    if (!initShaders(gl, vs_source, fs_source)) {
        console.error("Failed init Shader");
        return;
    }

    let n = initVertexBuffers(gl)
    if (n < 0) {
        console.error("initVertexBuffer Failed");
        return;
    }

    // Set texture
    if (!initTextures(gl, n)) {
        console.log('Failed to intialize the texture.');
        return;
    }

    gl.clearColor(0, 0, 0.5, 1);
    var tick = function () {
        let texCooord =  moveTexCord(gl,0.01)
        draw(gl, n,texCooord);
        requestAnimationFrame(tick);
    }
    tick();
}